<?php
// +----------------------------------------------------------------------
// | zhanshop-php / UserService.php    [ 2025/1/13 11:27 ]
// +----------------------------------------------------------------------
// | Copyright (c) 2011~2025 zhangqiquan All rights reserved.
// +----------------------------------------------------------------------
// | Author: zhangqiquan <768617998@qq.com>
// +----------------------------------------------------------------------
declare (strict_types=1);

namespace app\api\index\v1\service;

use app\constant\ApiCode;
use zhanshop\App;

class UserService
{
    /**
     * 获取用户信息
     * @param string $app
     * @param int $userId
     * @return array|mixed|string
     * @throws \Exception
     */
    public function getInfo(string $app, int $userId)
    {
        $userInfo = App::database()->model("user_info")->where(['app' => $app, 'user_id' => $userId])->find();
        if($userInfo == false) App::error()->setError($app.'没有'.$userId.'的相关数据', ApiCode::EXPECTATION_FAILED);
        if($userInfo['nick'] == false) $userInfo['nick'] = $app.$userId;
        return $userInfo;
    }
    protected $editField = ['avater', 'nick', 'birthday', 'sex'];
    /**
     * 获取用户信息
     * @param string $app
     * @param int $userId
     * @return array|mixed|string
     * @throws \Exception
     */
    public function postInfo(string $app, int $userId, array $data)
    {
        $updateData = [];
        foreach ($this->editField as $k => $v){
            if(isset($data[$k]) && $data[$k]){
                $updateData[$k] = $data[$k];
            }
        }
        if($updateData) App::database()->model("user_info")->where(['app' => $app, 'user_id' => $userId])->update($updateData);
    }
    /**
     * 注销用户信息
     * @param string $app
     * @param int $userId
     * @return array|mixed|string
     * @throws \Exception
     */
    public function deleteInfo(string $app, int $userId)
    {
        App::database()->model("user_info")->where(['app' => $app, 'user_id' => $userId])->update(['avater' => '', 'nick' => '', 'birthday' => '', 'vip_endtime' => 0, 'cancel_time' => time()]);
    }
}